<template>
  <div class="home">
    <!-- 筛选 -->
    <div class="search_content">
      <van-nav-bar :title="$route.meta.title" left-text="返回" left-arrow @click-left="onClickLeft" />
      <van-search v-model="requestParams.codeNo" placeholder="请输入车架号或者车牌号" shape="round" @search="initData"
        @clear="clearSearch" />
      <div class="search_item">
        <van-dropdown-menu :close-on-click-outside="false">
          <van-dropdown-item title="上次进场时间" ref="accidentRef">
            <div class="searchbox">
              <div class="insureList">
                <van-field v-model="requestParams.lastStartDate" label="开始时间" :placeholder="'请选择'" input-align="right"
                  readonly right-icon="arrow" @click="showPickerDate = true" />
                <van-field v-model="requestParams.lastEndDate" label="结束时间" :placeholder="'请选择'" input-align="right"
                  readonly right-icon="arrow" @click="showPickerDate1 = true" />
              </div>
              <div class="insureBtn">
                <van-button size="small" type="warning" class="resetBtn" @click="handleAccidentReset()">
                  重置
                </van-button>
                <van-button size="small" type="info" class="confirmBtn" @click="onConfirm('accidentRef')">
                  确认
                </van-button>
              </div>
            </div>
          </van-dropdown-item>

          <van-dropdown-item title="所属服务顾问" ref="insureRef">
            <div class="searchbox">
              <van-field v-model="requestParams.fixCenterName" name="维修中心" label="维修中心" input-align="right"
                placeholder="请选择" readonly right-icon="arrow" @click="handleSelect('fixCenterId', 'fixCenterName')" />
              <van-field v-model="requestParams.serverPsnName" name="服务顾问" label="服务顾问" input-align="right"
                placeholder="请选择" readonly right-icon="arrow" @click="handleSelect('serverPsnId', 'serverPsnName')" />

              <div class="insureBtn">
                <van-button size="small" type="warning" class="resetBtn" @click="handleReset()">
                  重置
                </van-button>
                <van-button size="small" type="info" class="confirmBtn" @click="onConfirm('insureRef')">
                  确认
                </van-button>
              </div>
            </div>
          </van-dropdown-item>

          <van-dropdown-item title="筛选" ref="searchRef">
            <div class="searchbox">
              <van-field name="radio" label="是否有待使用卡券" input-align="right" label-width="170px">
                <template #input>
                  <van-radio-group v-model="requestParams.isUsedCoo" direction="horizontal">
                    <van-radio :name="item.code" v-for="(item, index) in carCouponList" :key="index">
                      {{ item.name }}
                    </van-radio>
                  </van-radio-group>
                </template>
              </van-field>
              <!-- <div class="title">是否有待使用卡券</div>
              <div class="insureList">
                <div
                  class="insure_item"
                  :class="index == carCouponIndex ? 'active' : ''"
                  v-for="(item, index) in carCouponList"
                  :key="index"
                  @click="handleCarSelect(index, 'carCouponList')"
                >
                  {{ item.name }}
                </div>
              </div> -->
              <van-field v-model="requestParams.customerName" name="车主" label="车主" input-align="right"
                placeholder="请输入车主姓名" />
              <div class="insureBtn">
                <van-button size="small" type="warning" class="resetBtn" @click="handleSelectReset()">
                  重置
                </van-button>
                <van-button size="small" type="info" class="confirmBtn" @click="onConfirm('searchRef')">
                  确认
                </van-button>
              </div>
            </div>
          </van-dropdown-item>
        </van-dropdown-menu>
        <van-popup v-model="showPickerDate" position="bottom">
          <van-datetime-picker v-model="currentDate" type="date" @cancel="onCancelDate" @confirm="onConfirmDate"
            :formatter="formatter" />
        </van-popup>
        <van-popup v-model="showPickerDate1" position="bottom">
          <van-datetime-picker v-model="currentDate1" type="date" @cancel="onCancelDate1" @confirm="onConfirmDate1"
            :formatter="formatter" />
        </van-popup>

        <!-- 服务顾问 -->
        <van-popup v-model="showSelectPicker" position="bottom">
          <van-field name="模糊查询" input-align="left" v-model="likeWho" label="模糊查询" v-if="likeWhoField == 'fixCenterId' ||
            likeWhoField == 'serverPsnId'
            " placeholder="请输入模糊查询关键词" />
          <van-picker show-toolbar :columns="columns" @confirm="handleSelectConfirm" @cancel="showSelectPicker = false"
            value-key="name" />
        </van-popup>
      </div>
    </div>

    <!-- 列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="loadData"
        v-if="recordList && recordList.length != 0">
        <div class="orderList" v-if="recordList && recordList.length != 0">
          <div class="orderItem" v-for="(item, index) in recordList" :key="index">
            <div class="car_memberTies" v-if="item.memberTies">
              {{ item.memberTies ? '已绑车' : '' }}
            </div>
            <div class="orderItem_header">
              <div class="orderItem_lt" @click="goDetail(item)">
                <div class="carNo">
                  {{ item.carNo }}
                  <i @click.stop="handleCopy(item.carNo)" class="iconfont icon-copy"></i>
                  <i @click.stop="editCarNo(item)" class="iconfont icon-edit"></i>
                  <!-- <div class="car_vip" v-if="item.rmember">
                    {{ item.rmember ? 'VIP客户' : '' }}
                  </div> -->
                </div>
                <div class="carVin">
                  {{ item.vinCode }}
                  <i @click.stop="handleCopy(item.vinCode)" class="iconfont icon-copy"></i>
                </div>
              </div>

              <div class="orderItem_rt">
                <span @click="showTelbox(item)">
                  <i class="iconfont icon-tel"></i>
                </span>
                <div class="iconfont icon-wx" @click.stop="getExList(item)"></div>
              </div>
            </div>
            <div class="orderItem_content" @click="goDetail(item)">
              <div class="orderItem_data">
                <div class="order_label">车主</div>
                <div class="txt">
                  {{ item.ctmNumName ? item.ctmNumName : '-' }}
                </div>
              </div>
              <div class="orderItem_data">
                <div class="order_label">客户管家</div>
                <div class="txt">
                  {{ item.cusButName ? item.cusButName : '-' }}
                </div>
              </div>
              <div class="orderItem_data">
                <div class="order_label">服务顾问</div>
                <div class="txt">
                  {{ item.serverPsnName ? item.serverPsnName : '-' }}
                </div>
              </div>
              <div class="orderItem_data">
                <div class="order_label txtW">车型</div>
                <div class="txt ">
                  {{ item.carModelNameName ? item.carModelNameName : '-' }}
                </div>
              </div>

              <div class="orderItem_data time">
                <div class="order_label">
                  当前里程
                  <i @click.stop="mileRecord(item.billId)" class="iconfont icon-tips"></i>
                </div>
                <div class="txt">
                  {{ item.currCarMile || item.currCarMile == 0 ? item.currCarMile + 'km' : '-' }}
                </div>
              </div>
              <!-- <div class="orderItem_data time">
                <div class="order_label">上次进场里程</div>
                <div class="txt">
                  {{ item.carMile ? item.carMile + 'km' : '-' }}
                </div>
              </div> -->

              <div class="orderItem_data time">
                <div class="order_label">上次进场时间</div>
                <div class="txt">{{ item.lastIn ? item.lastIn : '-' }}</div>
              </div>
            </div>
            <div class="orderItem_file">
              <div class="file_item" @click="showUpdateTel(item)">
                <i class="iconfont icon-tel"></i>
                更新电话
              </div>
              <div class="file_item" @click="showUpdateMileage(item)">
                <i class="iconfont icon-mileage"></i>
                更新里程
              </div>
              <div class="file_item" @click="showUpdateService(item)">
                <i class="iconfont icon-gw"></i>
                变更顾问
              </div>
            </div>
          </div>
        </div>
      </van-list>
      <van-empty class="noContent" description="暂无数据" v-else />
    </van-pull-refresh>

    <div class="addBtn">
      <div class="orderItem_filebox" @click="addCar">
        <i class="iconfont icon-add"></i>
        新增车辆
      </div>
    </div>
    <div class="loading" v-if="loading">
      <van-loading size="30px" class="loadbox" color="#fff" text-color="#fff">
        加载中...
      </van-loading>
      <div class="mask"></div>
    </div>

    <!-- 更新联系电话 -->
    <van-dialog v-model="updateTelVisible" title="更新联系电话" show-cancel-button @confirm="updateTelConfirm"
      :before-close="beforeCloseUpdateTel">
      <van-field v-model="updateTelData.telTypeName" name="更新电话类型" label="更新电话类型" input-align="right" placeholder="请选择"
        readonly right-icon="arrow" @click="handleUpdateSelect('updateTelData', 'telType', 'telTypeName')" />
      <van-field v-model="updateTelData.currentTel" name="客户联系电话" :label="`当前${updateTelData.telTypeName}`"
        input-align="right" readonly />
      <van-field v-model="updateTelData.contactPhone" name="变更电话" :label="`变更${updateTelData.telTypeName}`"
        input-align="right" placeholder="请输入电话号码" />
    </van-dialog>

    <!-- 更新里程 -->
    <van-dialog v-model="updateMileageVisible" title="更新里程" show-cancel-button @confirm="updateMileageConfirm"
      :before-close="beforeCloseUpdateTel">
      <!-- <van-field
        v-model="updateMileageData.lastIn"
        name="登记时间"
        label="登记时间"
        input-align="right"
        readonly
      /> -->
      <van-field v-model="updateMileageData.currentMileage" name="当前里程" label="当前里程" input-align="right" readonly>
        <template slot="button">km</template>
      </van-field>
      <van-field v-model="updateMileageData.carMile" name="最新里程数" label="最新里程数" input-align="right" placeholder="请输入最新里程">
        <template slot="button">km</template>
      </van-field>
    </van-dialog>

    <!-- 变更顾问 -->
    <van-dialog v-model="updateServiceVisible" title="更新顾问" show-cancel-button @confirm="updateServiceConfirm"
      :before-close="beforeCloseUpdateTel">
      <van-field v-model="updateServiceData.fixCenterName" name="所属维修中心" label="所属维修中心" input-align="right"
        placeholder="请选择" readonly right-icon="arrow" @click="
          handleUpdateSelect(
            'updateServiceData',
            'fixCenterId',
            'fixCenterName',
          )
          " />
      <van-field v-model="updateServiceData.currentServerPsnName" name="当前顾问" label="当前顾问" input-align="right" readonly />
      <van-field v-model="updateServiceData.serverPsnName" name="请选择服务顾问" label="请选择服务顾问" label-width="130px"
        input-align="right" placeholder="请选择" readonly right-icon="arrow" @click="
          handleUpdateSelect(
            'updateServiceData',
            'serverPsnId',
            'serverPsnName',
          )
          " />
    </van-dialog>

    <van-popup v-model="updateSelectVisible" position="bottom">
      <van-picker show-toolbar :columns="updateColumns" @confirm="handleUpdateSelectConfirm"
        @cancel="updateSelectVisible = false" value-key="name" />
    </van-popup>
    <van-dialog v-model="showDialog" title="" show-cancel-button :showConfirmButton="false">
      <div class="contact_list">
        <div class="contact_item flex" v-for="(item, index) in contactList" :key="index">
          <div class="contact_lt flex">
            <img v-if="item.avatar" class="contact_header" :src="item.avatar" />
            <div class="contact_name">
              {{ item.remark ? item.remark : item.name }}
            </div>
            <div class="contact_com_wx" v-if="item.type == 1">@微信</div>
            <div class="contact_com" v-if="item.type == 2">
              @{{ item.corpName ? item.corpName : item.corpFullName }}
            </div>
          </div>
          <div class="contact_btn" @click="runWxChat(item)">联系</div>
        </div>
      </div>
    </van-dialog>

    <!-- 更新车牌号 -->
    <van-dialog v-model="editCarNoVisible" title="变更车牌号" show-cancel-button @confirm="handleUpdateCarNo"
      :before-close="beforeCloseUpdateTel">
      <van-field v-model="updateCarNoData.carNo" name="当前车牌号码" label="当前车牌号码" input-align="right" readonly></van-field>
      <van-field v-model="updateCarNoData.newCarNo" name="最新车牌号码" label="最新车牌号码" input-align="right"></van-field>
    </van-dialog>

    <!-- 变更记录 -->
    <van-dialog v-model="mileVisible" title="里程更新记录" show-cancel-button :showConfirmButton="false"
      @cancel="mileVisible = false" cancel-button-text="确认">
      <div class="auditbox">
        <div class="followInfo" v-if="mileList && mileList.length != 0">
          <table class="mileList">
            <tr class="mile_item_title">
              <th>更新人</th>
              <th>更新时间</th>
              <th>更新前</th>
              <th>更新后</th>
            </tr>
            <tr class="mile_item_val" v-for="(item, index) in mileList" :key="index">
              <td>{{ item.updateUser ? item.updateUser : '-' }}</td>
              <td>{{ item.updateTime ? item.updateTime : '-' }}</td>
              <td>{{ item.oldCarMile ? item.oldCarMile + 'km' : '0km' }}</td>
              <td>{{ item.carMile ? item.carMile + 'km' : '0km' }}</td>
            </tr>
          </table>
        </div>
        <van-empty class="noContent mileTop" description="暂无数据" v-else />
      </div>
    </van-dialog>

    <!-- 电话 -->
    <van-dialog v-model="telVisible" title="" show-cancel-button :showConfirmButton="false" @cancel="telVisible = false"
      cancel-button-text="取消">
      <div class="telbox">
        <div class="tel_item">
          <div class="tel_itembox">
            <div class="tel_icon">车主</div>
            <div class="txt">
              {{ userData.ownerName ? userData.ownerName : '暂无数据' }}
            </div>
            <div class="txt">
              {{ userData.ownerPhone ? userData.ownerPhone : '暂无数据' }}
            </div>
          </div>
          <div @click="handleTel(userData.ownerPhone)" class="tel_btn">
            呼叫
          </div>
        </div>
        <div class="tel_item">
          <div class="tel_itembox">
            <div class="tel_icon">送修人</div>
            <div class="txt">
              {{ userData.contactPeople ? userData.contactPeople : '暂无数据' }}
            </div>
            <div class="txt">
              {{ userData.contactPhone ? userData.contactPhone : '暂无数据' }}
            </div>
          </div>
          <div @click="handleTel(userData.contactPhone)" class="tel_btn">
            呼叫
          </div>
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import {
  Search,
  DropdownMenu,
  DropdownItem,
  Empty,
  Dialog,
  Toast,
  Notify,
  Loading,
} from 'vant'
import {
  getCookies,
  getCurrentTime,
  isPhone,
  copyToClipboard,
} from '../../utils/util'
import carApi from '@/api/carApi'
import commonApi from '@/api/commonApi'
import axios from 'axios'
import qs from 'qs'
const base_url = process.env.BASE_API
export default {
  name: 'carOrder',
  components: {
    Search,
    DropdownMenu,
    DropdownItem,
    Empty,
    Dialog,
    Toast,
    Notify,
    Loading,
  },
  data() {
    return {
      value: '',
      carCouponList: [
        { name: '是', code: 1, check: false },
        { name: '否', code: 0, check: false },
      ],
      showPickerDate: false,
      showPickerDate1: false,
      currentDate: new Date(),
      currentDate1: new Date(),

      recordList: [
        // {
        //   billId: "1", //单据ID
        //   vinCode: "Lasdad", //车架号
        //   carNo: "闽D12313", //车牌号
        //   ctmNumId: "1", //客户ID
        //   ctmNumPhone: "18718273123", //客户电话
        //   ctmNumName: "黄三", //客户名称
        //   ctmNumNumber: "123", //客户编码
        //   serverPsnId: "1", //所属服务顾问ID
        //   serverPsnName: "张三", //所属服务顾问名字
        //   serverPsnNumber: "1", //所属服务顾问编码
        //   carModelId: "1", //车型ID
        //   carModelName: "凯迪拉克", //车型名称
        //   carModelNumber: "11", //车型编码
        //   lastIn: "2022-09-09", //上次进场时间
        //   carMile: "19912", //行驶里程数
        // },
      ],
      columns: [],
      showSelectPicker: false,
      requestParams: {
        codeNo: '', //车架号或者车牌号，String，必填
        pageNo: 1, //当前页数，默认从1开始，每页显示十条，int，不能为空或者小于1
        lastStartDate: '', //上次进场开始时间，日期yyyy-MM-dd
        lastEndDate: '', //上次进场结束时间，日期yyyy-MM-dd
        fixCenterId: '', //维修中心ID值
        fixCenterName: '',
        serverPsnId: '', //所属服务顾问，ID值
        serverPsnName: '',
        customerName: '', //客户名称，模糊查询
        isUsedCoo: '', //是否有待使用券，1为是
        userId: getCookies('userId'), //用户ID，必填，String
      },

      carCouponIndex: null,
      // 更新电话字段
      updateTelVisible: false,
      updateTelData: {
        telType: '1',
        currentTel: '',
        contactPhone: '',
        id: '',
        userId: '',
        telTypeName: '车主电话',
        telData: {},
      },
      telTypeList: [
        { name: '车主电话', billId: 1 },
        { name: '送修电话', billId: 2 },
      ],

      // 下拉选项字段
      updateSelectVisible: false,
      updateDataField: '',
      updateDataChirldenField: '',
      updateDataChirldenFieldName: '',
      updateColumns: [],
      // 更新里程字段
      updateMileageVisible: false,
      updateMileageData: {
        lastIn: '',
        currentMileage: '',
        carMile: '',
        id: '',
        userId: '',
      },
      // 变更顾问字段
      updateServiceVisible: false,
      updateServiceData: {
        fixCenterId: '',
        fixCenterName: '',
        currentServerPsnName: '',
        serverPsnName: '',
        serverPsnId: '',
        id: '',
        userId: '',
      },
      repairCenterList: [
        { name: '厦门路虎', code: 1 },
        { name: '厦门捷豹', code: 2 },
      ],
      serviceList: [
        { name: '黄某某', code: 1 },
        { name: '张某某', code: 2 },
      ],
      // 分页参数
      loading: false,
      finished: false,
      refreshing: false,
      isLoadData: false,
      fixCenterList: [],
      field: '',
      fieldName: '',
      showDialog: false,
      contactList: [],
      editCarNoVisible: false,
      //
      updateCarNoData: {
        carNo: '',
        newCarNo: '',
        id: '',
      },
      mileList: [
        // {
        //   billId: '', //单据ID
        //   updateUser: '章三', //更新人
        //   updateTime: '2023-09-09', //更新时间
        //   carMile: '1000', //更新后
        //   oldCatMile: '9000', //更新前
        // },
      ],
      mileVisible: false,
      telVisible: false,
      userData: {},
      likeWho: "",
      likeWhoField: ''
    }

  },
  watch: {
    likeWho: function (nval, oval) {
      if (this.likeWhoField == 'fixCenterId') {
        if (nval) {
          let newArr = this.fixCenterList.filter((item) => {
            return item.name.indexOf(nval) > -1
          })
          console.log(newArr)
          this.columns = newArr
        } else {
          this.columns = this.fixCenterList
        }
      }
      if (this.likeWhoField == 'serverPsnId') {
        if (nval) {
          let newArr = this.empList.filter((item) => {
            return item.name.indexOf(nval) > -1
          })
          console.log(newArr)
          this.columns = newArr
        } else {
          this.columns = this.empList
        }
      }
    },
  },
  mounted() {
    this.initData()
    this.getMainFixCenter()
  },
  activited() { },

  methods: {
    // 获取外部联系人信息
    getExList(data) {
      axios({
        url: `${base_url}/proxy/ext/user/getExList`,
        method: 'post',
        data: qs.stringify(
          // { url: 'http://wycl.autocnd.com:41080/ysc/assessManageDetail' },
          { carNo: data.carNo, name: data.ctmNumName },
          { encode: false },
        ),
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          satoken: getCookies('token'),
        },
      }).then((res) => {
        if (res.data && res.data.data && res.data.data.length != 0) {
          this.contactList = res.data.data
          this.showDialog = true
        } else {
          Notify({ type: 'danger', message: '未找到相关联系人' })
        }

        console.log('获取外部联系人信息:', res)
      })
    },
    runWxChat(data) {
      let vm = this
      axios({
        url: `${base_url}/proxy/qywx/jsdkConfig`,
        method: 'post',
        data: qs.stringify(
          // { url: 'http://wycl.autocnd.com:41080/ysc/assessManageDetail' },
          { url: location.href.split('?')[0], type: 'app' },
          { encode: false },
        ),
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          satoken: getCookies('token'),
        },
      }).then((res) => {
        console.log('jsdkConfig:', res)
        let jsdk = res.data.data
        localStorage.setItem('jsdk', JSON.stringify(res.data.data))
        wx.agentConfig({
          corpid: jsdk.corpid, // 必填，企业微信的corpid，必须与当前登录的企业一致
          agentid: jsdk.agentid, // 必填，企业微信的应用id （e.g. 1000247）
          timestamp: jsdk.timestamp, // 必填，生成签名的时间戳
          nonceStr: jsdk.nonceStr, // 必填，生成签名的随机串
          signature: jsdk.signature, // 必填，签名，见附录-JS-SDK使用权限签名算法
          jsApiList: ['openEnterpriseChat'], //必填，传入需要使用的接口名称
          success: function (res) {
            console.log('agentConfig权限成功返回信息:', res)
            wx.openEnterpriseChat({
              // 注意：userIds和externalUserIds至少选填一个。内部群最多2000人；外部群最多500人；如果有微信联系人，最多40人
              userIds: '', //参与会话的企业成员列表，格式为userid1;userid2;...，用分号隔开。
              externalUserIds: data.externalUserid, // 参与会话的外部联系人列表，格式为userId1;userId2;…，用分号隔开。
              groupName: '', // 会话名称。单聊时该参数传入空字符串""即可。
              chatId: '', // 若要打开已有会话，需指定此参数。如果是新建会话，chatId必须为空串
              success: function (res) {
                var chatId = res.chatId //返回当前群聊ID，仅当使用agentConfig注入该接口权限时才返回chatId
                // 回调
              },
              fail: function (res) {
                if (res.errMsg.indexOf('function not exist') > -1) {
                  alert('版本过低请升级')
                }
              },
            })
          },
          fail: function (res) {
            console.log('agentConfig权限失败返回信息:', res)
            if (res.errMsg.indexOf('function not exist') > -1) {
              alert('版本过低请升级')
            }
          },
        })
      })
    },
    onClickLeft() {
      this.$router.go(-1)
    },
    // 初始化列表
    initData() {
      this.requestParams.pageNo = 1
      this.loadData()
    },
    // 获取列表
    loadData() {
      if (this.isLoadData) return
      this.isLoadData = true
      this.loading = true
      this.finished = false
      carApi.getCarInfoList({ ...this.requestParams }).then((res) => {
        console.log(res.data)

        if (this.requestParams.pageNo == 1) {
          this.recordList = res.data || []
        } else {
          this.recordList = this.recordList.concat(res.data || [])
        }
        this.requestParams.pageNo += 1
        if ((res.data && res.data.length == 0) || res.data == null) {
          this.finished = true
          this.isLoadData = true
        }
        // if (res.data.length < 10) {
        //   this.finished = true;
        //   this.isLoadData = true;
        // }
        this.isLoadData = false
        this.loading = false
      })
    },
    // 下拉刷新
    onRefresh() {
      // 清空列表数据
      this.recordList = []
      this.finished = false
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
      this.refreshing = false
      this.initData()
    },
    // 获取维修中心
    getMainFixCenter() {
      commonApi
        .getMainFixCenter({
          userId: this.requestParams.userId,
          type: 'fixCenter',
        })
        .then((res) => {
          if (res.data) {
            this.fixCenterList = res.data
          }
        })
    },
    // 获取服务人员
    getEmpPerson() {
      console.log(this.updateServiceData)

      commonApi
        .getEmpPerson({
          fixCenterId: this.updateServiceVisible
            ? this.updateServiceData.fixCenterId
            : this.requestParams.fixCenterId,
          userId: this.requestParams.userId,
        })
        .then((res) => {
          if (res.data) {
            this.empList = res.data
          }
        })
    },
    // 选择下拉
    handleSelect(field, fieldName) {

      if (field == 'carCoupon') {
        this.columns = [
          { name: '是', value: 1 },
          { name: '否', value: 2 },
        ]
      } else if (field == 'serverPsnId') {
        if (!this.requestParams.fixCenterId) {
          Toast('请先选择维修中心')
          return;
        }
        this.columns = this.empList
      } else if (field == 'fixCenterId') {
        this.columns = this.fixCenterList
      }
      this.showSelectPicker = true

      this.likeWhoField = field
      this.field = field
      this.fieldName = fieldName
    },

    // 筛选是否
    handleCarSelect(index) {
      this.carCouponIndex = index
    },
    // 筛选重置
    handleSelectReset() {
      this.requestParams.isUsedCoo = ''
      this.requestParams.customerName = ''
    },

    // 选择下拉确认
    handleSelectConfirm(value, index) {
      this.requestParams[this.field] = value.billId
      this.requestParams[this.fieldName] = value.name
      this.showSelectPicker = false
      if (this.field == 'fixCenterId') {
        this.getEmpPerson()
      }
      this.likeWho = ''
    },

    // 所属服务顾问重置
    handleReset() {
      console.log(1111)
      this.requestParams.fixCenterId = ''
      this.requestParams.fixCenterName = ''
      this.requestParams.serverPsnId = ''
      this.requestParams.serverPsnName = ''
    },

    //时间重置
    handleAccidentReset() {
      this.requestParams.lastStartDate = ''
      this.requestParams.lastEndDate = ''
    },
    onConfirm(ref) {
      // if (ref == "searchRef") {
      //   console.log(this.carCouponIndex);
      //   this.requestParams.isUsedCoo = this.carCouponIndex
      //     ? this.carCouponList[this.carCouponIndex].code
      //     : "";
      // }
      this.initData()
      this.$refs[ref].toggle()
    },
    onConfirmDate() {
      this.requestParams.lastStartDate = `${this.value1}-${this.value2}-${this.value3}` // 字符串拼接 结果入2020-07-03
      this.onCancelDate()
    },
    onConfirmDate1() {
      this.requestParams.lastEndDate = `${this.value1}-${this.value2}-${this.value3}` // 字符串拼接 结果入2020-07-03
      this.onCancelDate1()
    },
    onCancelDate() {
      this.showPickerDate = false
    },
    onCancelDate1() {
      this.showPickerDate1 = false
    },
    // 日期组件自定义格式
    formatter(type, value) {
      if (type === 'year') {
        this.value1 = value // 可以拿到当前点击的数值
        return `${value}年`
      } else if (type === 'month') {
        this.value2 = value
        return `${value}月`
      }
      this.value3 = value
      return `${value}日`
    },

    // 获取list名称
    getFieldName(list, key, val) {
      if (list && list.length > 0) {
        let obj = list.filter((item) => {
          return item[key] == val
        })
        if (obj.length > 0) {
          return obj[0].name
        }
      }
      return null
    },
    // 更新电话
    showUpdateTel(data) {
      this.updateTelVisible = true
      this.updateTelData.telTypeName = '车主电话'
      this.updateTelData.telType = '1'
      this.updateTelData.currentTel = data.ownerPhone
      this.updateTelData.id = data.billId
      this.updateTelData.telData = data
    },
    // 更新弹窗下拉
    handleUpdateSelect(data, field, fieldName) {
      this.updateSelectVisible = true
      this.updateDataField = data
      this.updateDataChirldenField = field
      this.updateDataChirldenFieldName = fieldName
      if (field == 'telType') {
        this.updateColumns = this.telTypeList
      }
      if (field == 'fixCenterId') {
        this.updateColumns = this.fixCenterList
      }
      if (field == 'serverPsnId') {
        this.updateColumns = this.empList
      }
    },
    // 更新下拉确认
    handleUpdateSelectConfirm(value) {
      this[this.updateDataField][this.updateDataChirldenFieldName] = value.name
      this[this.updateDataField][this.updateDataChirldenField] = value.billId
      if (this.updateDataField == 'updateServiceData') {
        this.getEmpPerson()
      }
      if (this.updateDataField == 'updateTelData') {
        if (value.billId == 1) {
          this.updateTelData.currentTel = this.updateTelData.telData.ownerPhone
        } else {
          this.updateTelData.currentTel = this.updateTelData.telData.contactPhone
        }
      }
      this.updateSelectVisible = false
    },

    // 更新电话确认
    updateTelConfirm() {
      if (!this.updateTelData.telType) {
        Notify({ type: 'danger', message: '请选择电话类型' })
        return
      } else {
        if (!this.updateTelData.contactPhone) {
          Notify({ type: 'danger', message: '请输入变更手机号' })
          return
        }
        if (this.updateTelData.telType == 1) {
          carApi
            .updateOwnerPhone({
              id: this.updateTelData.id, //单车表id，String，必填
              ownerPhone: this.updateTelData.contactPhone, //送修人电话，String，必填
              userId: this.requestParams.userId, //用户ID，必填，String
            })
            .then((res) => {
              if (res.code == 1) {
                this.initData()
                Notify({ type: 'success', message: '更新成功' })
              } else {
                Notify({ type: 'danger', message: res.errorMessage })
              }
            })
        } else if (this.updateTelData.telType == 2) {
          carApi
            .updateContactPhone({
              id: this.updateTelData.id, //单车表id，String，必填
              contactPhone: this.updateTelData.contactPhone, //送修人电话，String，必填
              userId: this.requestParams.userId, //用户ID，必填，String
            })
            .then((res) => {
              if (res.code == 1) {
                Notify({ type: 'success', message: '更新成功' })
                this.initData()
              } else {
                Notify({ type: 'danger', message: res.errorMessage })
              }
            })
        }
        this.updateTelVisible = false
      }

      this.clearDialogData()
    },
    beforeCloseUpdateTel(action, done) {
      if (action === 'confirm') {
        return done(false)
      } else {
        return done()
      }
    },
    // 更新里程弹窗
    showUpdateMileage(data) {
      this.updateMileageVisible = true
      this.updateMileageData.lastIn = data.lastIn
      this.updateMileageData.currentMileage = data.carMile
      this.updateMileageData.id = data.billId
    },
    // 清除弹窗信息
    clearDialogData() {
      console.log(this.updateMileageData)

      this.updateTelData = {
        telType: '1',
        currentTel: '',
        contactPhone: '',
        id: '',
        userId: '',
        telTypeName: '车主电话',
        telData: {},
      }
      this.updateMileageData = {
        time: '',
        currentMileage: '',
        editMileage: '',
        carMile: '',
        oldCarMile: '',
      }

      this.updateServiceData = {
        fixCenterId: '',
        fixCenterName: '',
        currentServerPsnName: '',
        serverPsnName: '',
        serverPsnId: '',
        id: '',
      }

      this.updateCarNoData = {
        carNo: '',
        newCarNo: '',
        id: '',
      }
    },
    // 更新里程确认
    updateMileageConfirm() {
      console.log(this.updateMileageData)
      if (!this.updateMileageData.carMile) {
        Notify({ type: 'danger', message: '请输入更新里程' })
        return
      }
      carApi
        .updateMiles({
          id: this.updateMileageData.id, //单车表id，String，必填
          carMile: this.updateMileageData.carMile, //送修人电话，String，必填
          userId: this.requestParams.userId, //用户ID，必填，String
          recordTime: getCurrentTime(),
          oldCarMile: this.updateMileageData.currentMileage,
        })
        .then((res) => {
          if (res.code == 1) {
            Notify({ type: 'success', message: '更新成功' })
            this.initData()
          } else {
            Notify({ type: 'danger', message: res.errorMessage })
          }
        })
      this.updateMileageVisible = false
      this.clearDialogData()
    },
    // 变更顾问
    showUpdateService(data) {
      this.updateServiceVisible = true
      this.updateServiceData.currentServerPsnName = data.serverPsnName
      this.updateServiceData.id = data.billId
      this.fixCenterList.forEach((item) => {
        if (item.billId == getCookies('orgId')) {
          this.updateServiceData.fixCenterId = item.billId
          this.updateServiceData.fixCenterName = item.name
        }
      })
      this.getEmpPerson()
    },
    // 变更顾问确认
    updateServiceConfirm() {
      console.log(this.updateServiceData)
      if (!this.updateServiceData.fixCenterId) {
        Notify({ type: 'danger', message: '请选择维修中心' })
        return
      }
      if (!this.updateServiceData.serverPsnId) {
        Notify({ type: 'danger', message: '请选择服务顾问' })
        return
      }
      carApi
        .updateSeverPsnAndFixCenter({
          id: this.updateServiceData.id, //单车表id，String，必填
          fixCenterId: this.updateServiceData.fixCenterId, //送修人电话，String，必填
          serverPsnId: this.updateServiceData.serverPsnId,
          userId: this.requestParams.userId, //用户ID，必填，String
        })
        .then((res) => {
          if (res.code == 1) {
            Notify({ type: 'success', message: '更新成功' })
            this.initData()
          } else {
            Notify({ type: 'danger', message: res.errorMessage })
          }
        })

      this.updateServiceVisible = false

      this.clearDialogData()
    },
    addCar() {
      this.$router.push('/addCar')
    },
    goDetail(data) {
      this.$router.push({
        path: '/carOrderDetail',
        query: { billId: data.billId, carNo: data.name },
      })
    },
    clearSearch() {
      this.requestParams.codeNo = ''
      this.initData()
    },
    handleTel(tel) {
      if (isPhone()) {
        window.location.href = `tel:${tel}`
      } else {
        Toast('请在手机端使用此功能')
      }
    },
    editCarNo(data) {
      this.editCarNoVisible = true
      this.updateCarNoData.carNo = data.carNo
      this.updateCarNoData.id = data.billId
    },
    handleUpdateCarNo() {
      if (!this.updateCarNoData.newCarNo) {
        Notify({ type: 'danger', message: '请输入最新车牌号' })
        return
      }
      carApi
        .updateCarNo({
          ...this.updateCarNoData,
        })
        .then((res) => {
          if (res.code == 1) {
            Notify({ type: 'success', message: '更新成功' })
            this.initData()
          } else {
            Notify({ type: 'danger', message: res.errorMessage })
          }
        })

      this.editCarNoVisible = false
      this.clearDialogData()
    },

    // 里程更新记录
    mileRecord(id) {
      this.mileList = []
      this.mileVisible = true
      carApi
        .getCarMilesRecord({
          id,
        })
        .then((res) => {
          if (res.code == 1) {
            this.mileList = res.data
          }
        })
    },
    showTelbox(data) {
      this.telVisible = true
      this.userData = data
    },
    handleCopy(data) {
      copyToClipboard(data)
      Toast('复制成功')
      // Notify({ type: 'success', message: '复制成功' })
    },
  },
}
</script>

<style lang="less" scoped="">
.home {
  background: #f3f3f3;
}

.search_content {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 2;
}

.searchbox {
  padding: 0.3rem;

  .title {
    font-size: 0.3rem;
    font-weight: bold;
    color: #333;
    margin-bottom: 0.4rem;
    padding-top: 0.2rem;
  }

  .insureList {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;

    .insure_item {
      text-align: center;
      padding: 0.15rem 0rem;
      width: 30%;
      box-sizing: border-box;
      font-size: 0.28rem;
      border-radius: 3px;
      color: #666;
      margin-bottom: 0.2rem;
      margin-right: 5%;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, 0.5);

      &:nth-child(3n) {
        margin-right: 0;
      }

      &.active {
        box-shadow: 0px 0px 3px 0px #f65e07;
        color: #f65e07;
      }
    }
  }

  .insureBtn {
    display: flex;
    justify-content: flex-end;

    margin-top: 0.4rem;

    .resetBtn {
      padding: 0 0.4rem;
      margin-right: 0.2rem;
    }

    .confirmBtn {
      padding: 0 0.4rem;
    }
  }
}

.orderList {
  padding-top: 3rem;
  margin: 0.3rem;
  overflow: hidden;

  .orderItem {
    padding: 0.2rem 0.3rem;
    background: #fff;
    border-radius: 10px;
    margin-bottom: 0.3rem;
    position: relative;
    overflow: hidden;

    .car_memberTies {
      position: absolute;
      background: rgba(32, 31, 98, 1);
      color: #fff;
      font-size: 0.24rem;
      right: -15px;
      top: -7px;
      padding: 2px 10px;
      padding-top: 15px;
      transform: rotate(40deg);
    }

    .orderItem_header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 0.1rem;
      border-bottom: 1px solid #f6f6f6;

      .orderItem_lt {
        .carNo {
          font-size: 0.3rem;
          color: #333;
          margin-right: 0.2rem;
          font-weight: bold;
          display: flex;
          align-items: center;
          user-select: auto;

          .icon-edit {
            font-size: 0.32rem;
            color: #999;
            margin-left: 0.1rem;
            position: relative;
            top: -1px;
          }
        }

        .carVin {
          font-size: 0.28rem;
          color: #999;
          margin-top: 0.15rem;
          user-select: auto;
        }

        .car_vip {
          padding: 5px 10px;
          background: rgba(220, 35, 38, 1);
          border-radius: 3px;
          color: #fff;
          font-size: 0.24rem;
          margin-left: 0.1rem;
          text-align: center;
        }

        .car_resSell {}
      }

      .orderItem_rt {
        display: flex;
        align-items: center;
        align-self: center;
        justify-content: flex-start;

        .txt {
          font-size: 0.28rem;
          color: #161616;
        }

        .icon-tel {
          font-size: 0.6rem;
          color: #35bc04;
          margin-right: 0.1rem;
          position: relative;
          top: -5px;
          // color: #fff;
          // background: #35bc04;
          // font-size: 0.32rem;
          // padding: 0.1rem;
          // border-radius: 50%;
          // margin-right: 0.2rem;
        }

        .icon-wx {
          color: #409eff;
          font-size: 0.65rem;
        }
      }
    }

    .orderItem_content {
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      align-items: center;

      .orderItem_data {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        width: 50%;
        margin-bottom: 0.1rem;
        font-size: 0.28rem;
        box-sizing: content-box;
        color: #333;

        .order_label {
          font-size: 0.28rem;
          color: #333;
          margin-right: 10px;
        }

        .txt {
          font-size: 0.28rem;
          color: #666;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .txtW {
          width: 40px;

        }

        &.time {
          width: 100%;
        }
      }
    }

    .orderItem_file {
      background: #ebebeb;
      color: #333;
      border-radius: 5px;
      padding: 0.1rem 0;
      text-align: center;
      width: 100%;
      font-size: 0.28rem;
      display: flex;
      align-items: center;
      justify-content: center;

      .file_item {
        width: 33.33%;
        border-right: 1px solid #ccc;

        .icon-tel {
          font-size: 0.34rem;
          color: #35bc04;
          margin-right: 0.1rem;
        }

        .icon-mileage {
          font-size: 0.4rem;
          color: #409eff;
          margin-right: 0.1rem;
          position: relative;
          top: 0.04rem;
        }

        .icon-gw {
          font-size: 0.4rem;
          color: #409eff;
          margin-right: 0.1rem;
          position: relative;
          top: 0.04rem;
        }

        &:last-child {
          border: none;
        }
      }
    }
  }
}

.addBtn {
  position: fixed;
  bottom: 0.8rem;
  width: 100%;
  z-index: 1;

  .orderItem_filebox {
    width: 2.8rem;
    margin: auto;
    text-align: center;
    font-size: 0.28rem;
    background: #409eff;
    color: #fff;
    padding: 0.25rem 0rem;
    border-radius: 50px;
  }
}

.noContent {
  margin-top: 2rem;
}

.contact_list {
  padding: 0.5rem 0.2rem 0 0.2rem;

  .contact_item {
    justify-content: space-between;
    margin-bottom: 20px;
  }

  .contact_lt {
    font-size: 0.28rem;
    color: #23ec1c;

    .contact_header {
      width: 30px;
      height: 30px;
      display: block;
      border-radius: 5px;
      margin-right: 5px;
    }

    .contact_name {
      font-size: 0.28rem;
      color: #333;
      margin-left: 5px;
    }

    .contact_com {
      color: #f65e07;
      font-size: 0.28rem;
    }

    .contact_com_wx {
      color: #23ec1c;
      font-size: 0.28rem;
    }
  }

  .contact_btn {
    background: #409eff;
    color: #fff;
    padding: 5px 15px;
    border-radius: 3px;
    font-size: 0.28rem;
  }
}

.auditbox {
  padding: 20px;

  .mileList {
    width: 100%;
  }

  .mile_item_title {
    font-size: 0.3rem;
    color: #333;
    padding: 10px 0;
  }

  .mile_item_val {
    text-align: center;
    font-size: 0.28rem;
    color: #999;

    td {
      padding: 10px 0;
    }
  }
}

.telbox {
  padding: 20px;

  .tel_item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;

    &:last-child {
      margin-bottom: 0;
    }

    .tel_itembox {
      display: flex;
      align-items: center;
    }

    .tel_icon {
      background: #409dfa;
      color: #fff;
      border-radius: 50%;
      height: 40px;
      width: 40px;
      text-align: center;
      line-height: 40px;
      font-size: 0.24rem;
      margin-right: 10px;
    }

    .txt {
      margin-right: 10px;
      font-size: 0.24rem;
      color: #666;
    }

    .tel_btn {
      background: #1c71c5;
      color: #fff;
      border-radius: 3px;
      padding: 0.2rem 10px;
      text-align: center;
      font-size: 0.24rem;
      margin-right: 10px;
    }
  }
}

.mileTop {
  padding: 0;
  margin-top: 0;
}

.icon-copy {
  margin-left: 5px;
  margin-right: 5px;
}
</style>
